<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('个人答题')" />
	<style>
		.question-card {
			margin-bottom: 20px;
			border: 1px solid #e8e8e8;
			border-radius: 4px;
			padding: 20px;
			background: #fff;
		}
		.question-title {
			font-size: 16px;
			font-weight: bold;
			margin-bottom: 15px;
			color: #333;
		}
		.question-options label {
			display: block;
			margin-bottom: 10px;
			cursor: pointer;
			padding: 8px;
			border-radius: 4px;
			transition: all 0.3s;
		}
		.question-options label:hover {
			background-color: #f0f9ff;
		}
		.question-options input[type="radio"] {
			margin-right: 8px;
		}
		.answer-selected {
			background-color: #e6f7ff !important;
			border-color: #1890ff !important;
		}
		.navigation-buttons {
			margin-top: 20px;
			text-align: center;
		}
		.timer-display {
			text-align: center;
			font-size: 18px;
			font-weight: bold;
			color: #f5222d;
			margin-bottom: 20px;
		}
		.progress-info {
			text-align: center;
			margin-bottom: 20px;
			color: #666;
		}
		.question-nav {
			display: inline-block;
			margin: 0 5px;
			width: 30px;
			height: 30px;
			line-height: 30px;
			text-align: center;
			border: 1px solid #d9d9d9;
			border-radius: 4px;
			cursor: pointer;
			transition: all 0.3s;
		}
		.question-nav:hover {
			border-color: #1890ff;
			color: #1890ff;
		}
		.question-nav.active {
			background-color: #1890ff;
			color: #fff;
			border-color: #1890ff;
		}
		.question-nav.answered {
			background-color: #52c41a;
			color: #fff;
			border-color: #52c41a;
		}
		.analysis-panel {
			margin-top: 15px;
			padding: 15px;
			background-color: #f6ffed;
			border: 1px solid #b7eb8f;
			border-radius: 4px;
			display: none;
		}
		.correct-answer {
			color: #52c41a;
			font-weight: bold;
		}
		.user-answer {
			color: #f5222d;
			font-weight: bold;
		}
		.fill-blank-input {
			display: inline-block;
			width: 150px;
			border: 1px solid #d9d9d9;
			border-radius: 4px;
			padding: 4px 11px;
			margin: 0 5px;
		}
	</style>
</head>
<body class="gray-bg">
	<div class="container-div">
		<div class="row">
			<div class="col-sm-12">
				<div class="ibox">
					<div class="ibox-title">
						<h5>答题界面</h5>
						<div class="ibox-tools">
							<a class="collapse-link">
								<i class="fa fa-chevron-up"></i>
							</a>
						</div>
					</div>
					<div class="ibox-content">
						<div class="timer-display" id="timer">
							剩余时间：<span id="time-display">00:00:00</span>
						</div>
						
						<div class="progress-info">
							<p>答题进度：<span id="current-num">1</span>/<span id="total-num">0</span></p>
						</div>
						
						<div class="question-area" id="question-area">
							<!-- 题目内容将通过JavaScript动态加载 -->
						</div>
						
						<div class="navigation-buttons">
							<button class="btn btn-default" id="prev-btn" onclick="prevQuestion()">
								<i class="fa fa-arrow-left"></i> 上一题
							</button>
							<div class="question-nav-list" id="question-nav-list" style="display: inline-block; margin: 0 20px;">
								<!-- 题目导航将通过JavaScript动态生成 -->
							</div>
							<button class="btn btn-default" id="next-btn" onclick="nextQuestion()">
								下一题 <i class="fa fa-arrow-right"></i>
							</button>
							<button class="btn btn-success" id="submit-btn" onclick="submitExam()" style="margin-left: 20px;">
								<i class="fa fa-check"></i> 提交答卷
							</button>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	
	<th:block th:include="include :: footer" />
	
	<script th:inline="javascript">
		var examData = {
			config: {
				id: /*[[${config.id}]]*/ 0,
				configName: /*[[${config.configName}]]*/ '',
				questionCount: /*[[${config.questionCount}]]*/ 0,
				examDuration: /*[[${config.examDuration}]]*/ 3600 // 默认1小时
			},
			questions: [],
			currentQuestionIndex: 0,
			answers: {}, // 用户答案记录
			timerInterval: null,
			remainingTime: 0
		};
		
		$(function() {
			// 初始化题目数据 - 使用HTML转义方式传递数据
			var questionsData = /*[[${questions}]]*/ [];
			console.log("从后端获取的题目数据:", questionsData);
			examData.questions = questionsData || [];
			
			// 设置考试时长
			examData.remainingTime = examData.config.examDuration;
			
			// 显示题目总数
			$('#total-num').text(examData.questions.length);
			
			// 初始化显示第一题
			if (examData.questions.length > 0) {
				showQuestion(0);
				updateQuestionNav();
				startTimer();
			} else {
				$('#question-area').html('<div class="alert alert-warning">该场次暂无题目，请联系管理员。</div>');
			}
		});
		
		// 显示指定题目
		function showQuestion(index) {
			if (index < 0 || index >= examData.questions.length) return;
			
			examData.currentQuestionIndex = index;
			var question = examData.questions[index];
			console.log("正在显示题目:", question);
			
			// 更新进度显示
			$('#current-num').text(index + 1);
			
			// 构造题目HTML
			var questionHtml = '<div class="question-card">';
			questionHtml += '<div class="question-title">第' + (index + 1) + '题：' + (question.questionName || '题目内容为空') + '</div>';
			questionHtml += '<div class="question-options">';
			
			// 根据题目类型显示不同界面
			if (question.questionType === 1 || question.questionType === 2) {
				// 单选题或多选题
				var options = ['A', 'B', 'C', 'D'];
				for (var i = 0; i < options.length; i++) {
					var optionKey = 'option' + options[i];
					var optionContent = question[optionKey];
					if (optionContent) {
						var isChecked = examData.answers[question.id] === options[i] ? 'checked' : '';
						var isSelectedClass = isChecked ? 'answer-selected' : '';
						questionHtml += '<label class="' + isSelectedClass + '" id="label-' + question.id + '-' + options[i] + '">';
						questionHtml += '<input type="radio" name="question-' + question.id + '" value="' + options[i] + '" ' + isChecked + 
									   ' onchange="selectAnswer(' + question.id + ', \'' + options[i] + '\')"> ' + 
									   options[i] + '. ' + optionContent;
						questionHtml += '</label>';
					}
				}
			} else if (question.questionType === 3) {
				// 判断题
				var trueChecked = examData.answers[question.id] === '正确' ? 'checked' : '';
				var falseChecked = examData.answers[question.id] === '错误' ? 'checked' : '';
				var trueClass = trueChecked ? 'answer-selected' : '';
				var falseClass = falseChecked ? 'answer-selected' : '';
				
				questionHtml += '<label class="' + trueClass + '" id="label-' + question.id + '-true">';
				questionHtml += '<input type="radio" name="question-' + question.id + '" value="正确" ' + trueChecked + 
							   ' onchange="selectAnswer(' + question.id + ', \'正确\')"> 正确';
				questionHtml += '</label>';
				
				questionHtml += '<label class="' + falseClass + '" id="label-' + question.id + '-false">';
				questionHtml += '<input type="radio" name="question-' + question.id + '" value="错误" ' + falseChecked + 
							   ' onchange="selectAnswer(' + question.id + ', \'错误\')"> 错误';
				questionHtml += '</label>';
			} else if (question.questionType === 4) {
				// 填空题
				var userAnswer = examData.answers[question.id] || '';
				questionHtml += '<input type="text" class="fill-blank-input" name="question-' + question.id + '" value="' + userAnswer + 
							   '" onchange="selectAnswer(' + question.id + ', this.value)" placeholder="请输入答案">';
			}
			
			questionHtml += '</div>'; // end question-options
			
			// 添加解析面板（默认隐藏）
			questionHtml += '<div class="analysis-panel" id="analysis-' + question.id + '">';
			questionHtml += '<p><strong>正确答案：</strong><span class="correct-answer">' + formatCorrectAnswer(question) + '</span></p>';
			questionHtml += '<p><strong>解析：</strong>' + (question.analysis || '暂无解析') + '</p>';
			questionHtml += '</div>';
			
			questionHtml += '</div>'; // end question-card
			
			$('#question-area').html(questionHtml);
			
			// 更新导航按钮状态
			updateNavigationButtons();
		}
		
		// 格式化正确答案显示
		function formatCorrectAnswer(question) {
			if (question.questionType === 4) {
				// 填空题
				return question.correctAnswer || '无标准答案';
			} else {
				// 其他题型
				return getOptionText(question.correctAnswer);
			}
		}
		
		// 选择答案
		function selectAnswer(questionId, option) {
			// 记录答案
			examData.answers[questionId] = option;
			
			// 更新选项样式（仅适用于单选/多选/判断题）
			var question = examData.questions.find(q => q.id == questionId);
			if (question && (question.questionType === 1 || question.questionType === 2 || question.questionType === 3)) {
				$('input[name="question-' + questionId + '"]').each(function() {
					var $label = $(this).parent();
					if (this.value === option) {
						$label.addClass('answer-selected');
					} else {
						$label.removeClass('answer-selected');
					}
				});
			} else if (question && question.questionType === 4) {
				// 填空题不需要特殊样式处理
			}
			
			// 更新题目导航状态
			updateQuestionNav();
		}
		
		// 获取选项文本
		function getOptionText(option) {
			var optionMap = {
				'1': 'A',
				'2': 'B',
				'3': 'C',
				'4': 'D'
			};
			return optionMap[option] || option;
		}
		
		// 更新导航按钮状态
		function updateNavigationButtons() {
			// 上一题按钮
			if (examData.currentQuestionIndex <= 0) {
				$('#prev-btn').prop('disabled', true);
			} else {
				$('#prev-btn').prop('disabled', false);
			}
			
			// 下一题按钮
			if (examData.currentQuestionIndex >= examData.questions.length - 1) {
				$('#next-btn').prop('disabled', true);
			} else {
				$('#next-btn').prop('disabled', false);
			}
		}
		
		// 上一题
		function prevQuestion() {
			if (examData.currentQuestionIndex > 0) {
				showQuestion(examData.currentQuestionIndex - 1);
			}
		}
		
		// 下一题
		function nextQuestion() {
			if (examData.currentQuestionIndex < examData.questions.length - 1) {
				showQuestion(examData.currentQuestionIndex + 1);
			}
		}
		
		// 更新题目导航
		function updateQuestionNav() {
			var navHtml = '';
			for (var i = 0; i < examData.questions.length; i++) {
				var questionId = examData.questions[i].id;
				var navClass = 'question-nav';
				if (i === examData.currentQuestionIndex) {
					navClass += ' active';
				}
				if (examData.answers[questionId]) {
					navClass += ' answered';
				}
				navHtml += '<div class="' + navClass + '" onclick="showQuestion(' + i + ')">' + (i + 1) + '</div>';
			}
			$('#question-nav-list').html(navHtml);
		}
		
		// 开始计时
		function startTimer() {
			updateTimerDisplay();
			examData.timerInterval = setInterval(function() {
				examData.remainingTime--;
				updateTimerDisplay();
				
				if (examData.remainingTime <= 0) {
					clearInterval(examData.timerInterval);
					$.modal.alertWarning('考试时间已结束，即将提交答卷');
					setTimeout(function() {
						submitExam();
					}, 2000);
				}
			}, 1000);
		}
		
		// 更新计时器显示
		function updateTimerDisplay() {
			var totalSeconds = examData.remainingTime;
			var hours = Math.floor(totalSeconds / 3600);
			var minutes = Math.floor((totalSeconds % 3600) / 60);
			var seconds = totalSeconds % 60;
			
			var timeStr = padZero(hours) + ':' + padZero(minutes) + ':' + padZero(seconds);
			$('#time-display').text(timeStr);
			
			// 时间少于10分钟时，高亮显示
			if (totalSeconds < 600) {
				$('#timer').css('color', '#f5222d');
			}
		}
		
		// 补零函数
		function padZero(num) {
			return num < 10 ? '0' + num : num;
		}
		
		// 提交考试
		function submitExam() {
			// 停止计时
			clearInterval(examData.timerInterval);
			
			// 计算成绩
			var correctCount = 0;
			var totalQuestions = examData.questions.length;
			
			// 构造用户答案字符串
			var userAnswers = "";
			for (var i = 0; i < examData.questions.length; i++) {
				var question = examData.questions[i];
				var userAnswer = examData.answers[question.id];
				if (userAnswer) {
					if (userAnswers !== "") {
						userAnswers += ",";
					}
					userAnswers += question.id + ":" + userAnswer;
				}
			}
			
			// 计算用时（秒）
			var useTime = examData.config.examDuration - examData.remainingTime;
			
			// 提交到后端
			$.ajax({
				url: ctx + 'system/exam/personal/submit',
				type: 'POST',
				data: {
					configId: examData.config.id,
					examType: 1, // 个人答题类型
					useTime: useTime,
					userAnswers: userAnswers
				},
				success: function(result) {
					if (result.code === 0) {
						// 显示结果
						var score = result.data.score;
						var resultMsg = '您答对了' + result.data.correctQuestion + '题，共' + result.data.totalQuestion + '题，得分：' + score + '分';
						$.modal.alertSuccess(resultMsg);
						
						// 跳转回首页
						setTimeout(function() {
							location.href = ctx + 'system/exam/personal/index';
						}, 2000);
					} else {
						$.modal.alertError('提交失败: ' + result.msg);
						// 重新开始计时
						startTimer();
					}
				},
				error: function() {
					$.modal.alertError('提交失败，请重试');
					// 重新开始计时
					startTimer();
				}
			});
		}
	</script>
</body>
</html>